package com.diandian.pos.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class HttpCallService {
    private static Logger log = LoggerFactory.getLogger(HttpCallService.class);

    /**
     * 支付宝支付
     * @param orderId
     * @param amount
     * @param authCode
     * @param requestUrl
     * @return
     */
    public static JSONObject doAliPay(String orderId, double amount, String authCode,String requestUrl) {
    	return orderPayment(orderId, amount, authCode, requestUrl);
    }
    
    /**
     * 微信支付
     * @param orderId
     * @param amount
     * @param authCode
     * @param requestUrl
     * @return
     */
    public static JSONObject wxMicroPay(String orderId, double amount, String authCode,String requestUrl) {
        return orderPayment(orderId, amount, authCode, requestUrl);
    }
    
    /**
     * 订单支付
     * @param orderId
     * @param amount
     * @param authCode
     * @param requestUrl
     * @return
     */
	private static JSONObject orderPayment(String orderId, double amount, String authCode, String requestUrl) {
		JSONObject result = new JSONObject();
        //String requestUrl = CustomizedPropertyConfigurer.getContextProperty("pay.url") + "/microPay/doWxPay";
        log.info("request url is {}",requestUrl);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(requestUrl);
        CloseableHttpResponse httpResponse = null;
        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("orderId",orderId));
            params.add(new BasicNameValuePair("authCode",authCode));
            params.add(new BasicNameValuePair("amount",String.valueOf(amount)));
            httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            httpResponse = httpClient.execute(httpPost);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                log.info("请求商户打款异常,待处理中");
                result.put("rest_code",1000);
                result.put("rest_msg", "点点支付网关返回结果异常，没有正常返回数据!");
                httpPost.abort();
            } else {
                log.info("数据返回正常");
                HttpEntity entity = httpResponse.getEntity();
                if (entity != null) {
                    String resp = EntityUtils.toString(entity, "utf-8");
                    result = JSONObject.parseObject(resp);
                    /*
                    JSONObject jsonObject = JSONObject.parseObject(resp);
                    result = jsonObject.getString("rest_code");
                    */
                    EntityUtils.consume(entity);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            result.put("rest_code",1000);
            result.put("rest_msg", "请求点点支付网关失败!");
        } finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }
        }
        log.info("账单id" +orderId + "处理结果为:" + result.toString());
        return result;
	}



    public static void refreshShopHeartBeat(final String shopId,final int tmpClose){
        ThreadUtils.invoke(new Runnable() {
            public void run() {
                refreshHeartBeatandle(String.valueOf(shopId), tmpClose);
            }
        });
    }

    private static String refreshHeartBeatandle(String shopId, int tmpClose) {
        String result = "";
        String requestUrl = CustomizedPropertyConfigurer.getContextProperty("mobile.url") + "/common/refreshHeartBeat?shopId=" + shopId+"&tmpClose="+tmpClose;
        log.info("request url is {}",requestUrl);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet(requestUrl);
        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(httpget);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                log.info("请求token 异常,待处理中");
                httpget.abort();
            } else {
                log.info("数据返回正常");
                HttpEntity entity = httpResponse.getEntity();
                if (entity != null) {
                    String resp = EntityUtils.toString(entity, "utf-8");
                    JSONObject jsonObject = JSONObject.parseObject(resp);
                    result = jsonObject.getString("rest_code");
                    EntityUtils.consume(entity);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }
        }
        log.info("请求心跳" + shopId + "更新结果为:" + result);
        return result;
    }


    public static void refreshShopDataCache(final String shopId){
        ThreadUtils.invoke(new Runnable() {
            public void run() {
            	refreshAllCacheHandle(String.valueOf(shopId));
            }
        });
    }
    
    
    private static String refreshAllCacheHandle(String shopId) {
        String result = "";
        String requestUrl = CustomizedPropertyConfigurer.getContextProperty("op.url") + "/shopinfo/manualRefresh?shop_id=" + shopId;
        try{
        	refreshCacheHandle(shopId,requestUrl);
        }catch(Exception e){
        	log.info("清除缓存失败",e);
        }
        return result;
    }
    
    /*
    private static String refreshAllCacheHandle(String shopId) {
        String result = "";
        
        String requestUrl = CustomizedPropertyConfigurer.getContextProperty("mobile.url") + "/common/refreshShopData?shopId=" + shopId+"&refresh=1";
        try{
        	refreshCacheHandle(shopId,requestUrl);
        }catch(Exception e){
        	log.info("清除缓存失败",e);
        }
        requestUrl = CustomizedPropertyConfigurer.getContextProperty("mobile.em.url") + "/common/refreshShopData?shopId=" + shopId+"&refresh=1";
        try{
        	refreshCacheHandle(shopId,requestUrl);
        }catch(Exception e){
        	log.info("清除缓存失败",e);
        }
        
        requestUrl = CustomizedPropertyConfigurer.getContextProperty("mobile.takeout.url") + "/common/refreshShopData?shopId=" + shopId+"&refresh=1";
        try{
        	refreshCacheHandle(shopId,requestUrl);
        }catch(Exception e){
        	log.info("清除缓存失败",e);
        }
        return result;
    }
    */
    
    
    
    private static String refreshCacheHandle(String shopId,String requestUrl) {
        String result = "";
        //String requestUrl = CustomizedPropertyConfigurer.getContextProperty("mobile.url") + "/common/refreshShopDataCache?shop_id=" + shopId;
        //String requestUrl = CustomizedPropertyConfigurer.getContextProperty("mobile.url") + "/common/refreshShopData?shopId=" + shopId+"&refresh=1";
        log.info("request url is {}",requestUrl);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet(requestUrl);
        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(httpget);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                log.info("请求token 异常,待处理中");
                httpget.abort();
            } else {
                log.info("数据返回正常");
                HttpEntity entity = httpResponse.getEntity();
                if (entity != null) {
                    String resp = EntityUtils.toString(entity, "utf-8");
                    JSONObject jsonObject = JSONObject.parseObject(resp);
                    result = jsonObject.getString("rest_code");
                    EntityUtils.consume(entity);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }
        }
        log.info("请求处理商家数据" + shopId + "结果为:" + result);
        return result;
    }
    
    
   
}

